package com.lx.crm.service.impl;

import com.lx.crm.entity.User;
import com.lx.crm.repository.UserRepository;
import com.lx.crm.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserRepository userRepository;
    @Override
    public Page<User> findPageByMap(Map param, Pageable pageable) {
        return userRepository.findAll(new Specification<User>(){

            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (param.get("userName")!=null){//动态SQL
                    predicates.add(criteriaBuilder.like(root.get("userName"),"%"+param.get("userName")+"%"));
                }
                if (param.get("userRoleId")!=null){
                    predicates.add(criteriaBuilder.equal(root.get("userRoleId"),param.get("userRoleId")));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        },pageable);
    }
}
